package com.tanhua.dubbo.api;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.model.mongo.Friend;
import com.tanhua.model.mongo.UserLike;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;
import java.util.stream.Collectors;

@DubboService
public class FriendApiImpl implements FriendApi{
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void save(Long friendId, Long userId) {
        Query query = Query.query(Criteria.where("userId").is(userId).and("friendId").is(friendId));
        if(!mongoTemplate.exists(query,Friend.class)){
            Friend friend = new Friend();
            friend.setUserId(userId);
            friend.setFriendId(friendId);
            friend.setCreated(System.currentTimeMillis());
            mongoTemplate.save(friend);
        }

        query = Query.query(Criteria.where("userId").is(friendId).and("friendId").is(userId));
        if (!mongoTemplate.exists(query, Friend.class)) {
            Friend friend = new Friend();
            friend.setUserId(friendId);
            friend.setFriendId(userId);
            friend.setCreated(System.currentTimeMillis());
            mongoTemplate.save(friend);
        }
    }

    @Override
    public void delete(Long friendId, Long userId) {
        Query query = Query.query(Criteria.where("userId").is(userId).and("friendId").is(friendId));
        mongoTemplate.remove(query, Friend.class);
        query = Query.query(Criteria.where("userId").is(friendId).and("friendId").is(userId));
        mongoTemplate.remove(query, Friend.class);
    }

    @Override
    public Boolean isLike(Long userId, Long friendId) {
        Query query = Query.query(Criteria.where("userId").is(userId).and("friendId").is(friendId));
        return mongoTemplate.exists(query, Friend.class);
    }

    @Override
    public void unFocus(Long userId, Long friendId) {
        Query query = Query.query(Criteria.where("userId").is(userId).and("friendId").is(friendId));
        mongoTemplate.remove(query, UserLike.class);
    }

    @Override
    public List<Long> findById(Long userId) {
        Query query = Query.query(Criteria.where("userId").is(userId));
        List<Friend> friends = mongoTemplate.find(query, Friend.class);
        return friends.stream().map(Friend::getFriendId).collect(Collectors.toList());
    }
}
